#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys, os, getopt, logging

# - This script takes a database-dump of the current OXID e-Shop database and saves in 
#   SHOPROOT/database/
# - It assumes directory-structure of standard  OXID CE 4. It's tested 
#   to work well up to 4.3.1
# - For questions contact oxid@euroblaze.de, or visit www.euroblaze.de

# - Globals.  (See some more defined in main())
MYSQL_DUMP 	= "/usr/bin/mysqldump"
my_db_credentials = {'db_host':'', 'db_port':'', 'db_name':'', 'db_user':'', 'db_pass':''}

# logging.basicConfig(filename='dbdump.log', level=logging.DEBUG)
# logging.basicConfig(format='%(levelname)s:%(asctime)s %(message)s', datefmt='%d.%m.%y %I:%M:%S', \
#					level=logging.DEBUG, filename=OX_SHOPROOT + '/log/' + sys.argv[0] + '.log')

def take_dump ():
	DUMP_COMMAND =  MYSQL_DUMP + " " + my_db_credentials['db_name'] + " -u" + \
					my_db_credentials['db_user'] + " -p" + my_db_credentials['db_pass'] + \
					" -h " + my_db_credentials['db_host'] + \
					" -P " + my_db_credentials['db_port'] + \
					" | grep -v '50013 DEFINER' > " + DB_FOLDER + "/" + \
					my_db_credentials['db_name'] + "_" + OX_ENV + ".sql"
	
	logging.debug(DUMP_COMMAND)
	os.system(DUMP_COMMAND)

# - Open OX_CONFIG and read lines for DB Host, Port, Name User, Password
def read_db_credentials ():
	import re
	# print "Reading OXID's %s for DB credentials..." % OX_CONFIG
	logging.info("Reading OXID's %s for DB credentials..." % OX_CONFIG)

	for conf_line in open(OX_CONFIG, 'r'):
        # DB Host and Port
		if ('$this->dbHost') in conf_line:
			my_db_credentials['db_host'] = conf_line

			p = re.compile('\$this\-\>dbHost\s*\=\s*\'')
			db_host = p.sub('', my_db_credentials['db_host'])

			p = re.compile('\'\;.*')
			db_host = p.sub('', db_host)

			my_db_credentials['db_host'] = db_host.strip()
            
			# Maybe there is a Port-number attached to Host
			if my_db_credentials['db_host'].find(':') > -1:
				my_db_credentials['db_port'] = my_db_credentials['db_host'].split(':')[1]
        my_db_credentials['db_host'] = my_db_credentials['db_host'].split(':')[0]
			else:
				my_db_credentials['db_port'] = '3306'

		# DB Name
		if ('$this->dbName') in conf_line:
			my_db_credentials['db_name'] = conf_line
	
			p = re.compile('\$this\-\>dbName\s*\=\s*\'')
			db_name = p.sub('', my_db_credentials['db_name'])
	
			p = re.compile('\'\;.*')
			db_name = p.sub('', db_name)
	
			my_db_credentials['db_name'] = db_name.strip()

		# DB User
		if ('$this->dbUser') in conf_line:
			my_db_credentials['db_user'] = conf_line

			p = re.compile('\$this\-\>dbUser\s*\=\s*\'')
			db_user = p.sub('', my_db_credentials['db_user'])

			p = re.compile('\'\;.*')
			db_user = p.sub('', db_user)

			my_db_credentials['db_user'] = db_user.strip()

		# DB Password
		if ('$this->dbPwd') in conf_line:
			my_db_credentials['db_pass'] = conf_line

			p = re.compile('\$this\-\>dbPwd\s*\=\s*\'')	# Remove PHP from 
														# front of the sought variable
			db_pass = p.sub('', my_db_credentials['db_pass'])

			p = re.compile('\'\;.*')		# Remove PHP code from back 
											# of the needed variable
			db_pass = p.sub('', db_pass)

			my_db_credentials['db_pass'] = db_pass.strip()

	# for db_key in my_db_credentials:
	#	print "%s = %s" % (db_key, my_db_credentials[db_key].rstrip('\n'))

# -- It is necessary that a couple of environment variables are available for this script to 
#    to know it's way around the OXID e-Shop environment
# def check_environ ():
	# if ( os.environ['OX_SHOPROOT'] == '' ):
		# print "You need to setup the OX_SHOPROOT environment variables on the SHELL "
		# sys.exit()
	# elif ( os.environ['OX_ENV'] == '' ):
		# print "You need to setup the OX_ENV environment variables on the SHELL "
		# sys.exit()

def usage ():
	print "Usage: %s -e <ENVIRONMENT> -s <SHOPROOT>" % sys.argv[0]

def main (argv):
	try:
		opts, args = getopt.getopt(argv, "e:s:", ["environ=", "shoproot="])
		
		global OX_ENV, OX_SHOPROOT, OX_CONFIG, DB_FOLDER

		for k, v in opts:
			if k in ("-e", "--environ"):
				OX_ENV	= v
			elif k in ("-s", "--shoproot"):
				OX_SHOPROOT = v
			else:
				assert False, "Unhandled option"
				usage()

		OX_CONFIG	= OX_SHOPROOT + '/config.inc.php'
		DB_FOLDER	= OX_SHOPROOT + "/database"

	except:
		usage()
		sys.exit(2)

	# logging.basicConfig(filename='dbdump.log', level=logging.DEBUG)
	logging.basicConfig(format='%(levelname)s:%(asctime)s %(message)s', datefmt='%d.%m.%y %I:%M:%S', \
						level=logging.DEBUG, filename=OX_SHOPROOT + '/log/eb_takedbdump.log')


if __name__ == "__main__":
	main (sys.argv[1:])

	read_db_credentials()
	take_dump()
